/*******************************************************************************
 * Copyright 2013 Mindaugas Idzelis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package incontrol.rcon.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class UInt32 {

	private long integer;

	public UInt32(long integer) {
		this.integer = integer;
	}

	// BF3 spec says to use little endian
	public void write(OutputStream out) throws IOException {
		out.write((int) integer);
		out.write((int) integer >> 8);
		out.write((int) integer >> 16);
		out.write((int) integer >> 24);
	}

	public static UInt32 read(InputStream in) throws IOException {
		byte[] bytes = new byte[4];
		in.read(bytes);
		long num = (bytes[0] & 0xFF) | (bytes[1] & 0xFF) << 8
				| (bytes[2] & 0xFF) << 16 | (bytes[3] & 0xFF) << 24;
		return new UInt32(num);
	}

	public static UInt32 read(InputStream in, boolean log) throws IOException {
		byte[] bytes = new byte[4];
		in.read(bytes);
		long num = (bytes[0] & 0xFF) | (bytes[1] & 0xFF) << 8
				| (bytes[2] & 0xFF) << 16 | (bytes[3] & 0xFF) << 24;
		if (log) {

			StringBuilder binary = new StringBuilder();
			for (byte b : bytes) {
				int val = b;
				for (int i = 0; i < 8; i++) {
					binary.append((val & 128) == 0 ? 0 : 1);
					val <<= 1;
				}
				binary.append(' ');
				binary.append("\n");
			}

			System.out.println(binary);
			System.out.println("=" + Long.toBinaryString(num));
		}
		return new UInt32(num);
	}

	public long getValue() {
		return integer;
	}
	// public static void main(String[] args) throws IOException {
	// long requestSeq = 1;
	// requestSeq |= 1 << 31;
	// requestSeq |= 0 << 30;
	//
	// ByteArrayOutputStream out = new ByteArrayOutputStream();
	// new UInt32(requestSeq).write(out);
	// ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	// UInt32 o = UInt32.read(in);
	// System.out.println("");
	//
	// }

}
